<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace api\controllers;

use Yii;

/**
 * Description of RegisterController
 *
 * @author Administrator
 */
class GetSmsController  extends \api\components\Controller {
    
    public function beforeAction($action) {
        
        $before = parent::beforeAction($action); 
        
        $request = new \yii\web\Request();
        $appname = $request->getHeaders()->get('appname');
        if ($appname && $appname == 'iot') {
            return $before;
        }
        elseif (! $this->checkCaptcha()){
            parent::afterAction($action, ['code' => 100021, 'message' => Yii::t('user', 'captcha fail')]);
            return FALSE;
        }
        return $before;
    }


    function checkCaptcha() {
        $captchaInput = Yii::$app->request->get('captcha'); 
        $validator = new \yii\captcha\CaptchaValidator(['captchaAction' => '/captcha/get-sms']);
        return $validator->validate($captchaInput);
    }

    public function actionRegister($mobile) {
        $user = \yiike\user\models\User::findOne(['username' => $mobile]);
        if ($user) {
            return ['code' => 100020];
        }
        
        list($code, $msg) = Yii::$app->smsValidator->send($mobile, 'register');
        return ['code' => $code, 'message' => $msg];
    }

    public function actionForgot($mobile) {
        $user = \yiike\user\models\User::findOne(['username' => $mobile]);
        if ($user) {
            list($code, $msg) = Yii::$app->smsValidator->send($mobile, 'forgot');
            return ['code' => $code, 'message' => $msg];            
        }
        else {
            return ['code' => 100031];
        }
    }
}

